package de.unimannheim.ki.tests;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import weka.associations.FPGrowth;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.experiment.InstanceQuery;
import de.umass.lastfm.Caller;
import de.umass.lastfm.PaginatedResult;
import de.umass.lastfm.Track;
import de.umass.lastfm.User;
import de.unimannheim.ki.algorithmn.LikeAssociationJoint;
import de.unimannheim.ki.algorithmn.NNAlgorithm;
import de.unimannheim.ki.algorithmn.Neighbour;
import de.unimannheim.ki.databaseentities.Musicuser;
import de.unimannheim.ki.databaseentities.Song;
import de.unimannheim.ki.usermanagement.DatabaseUserDAO;

public class ImportTestLastFM {

	private static String APIKEY = "7641e28f7cdec04671e0c3c19455dc8f";
	/**usertracks = new ArrayList<Track>();
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("start");
		DatabaseUserDAO dao = DatabaseUserDAO.getDAO();
		//List<Musicuser> allUsers = dao.getAllUsers();
		
		Musicuser testuser = dao.getUser("100001071382347");
			Instances data = null;
			InstanceQuery query = null;
			try {
				query = new InstanceQuery();
				query.setDatabaseURL("jdbc:mysql://localhost:3306/ebdb");
				System.out.println("DATABASE URL:::::"+query.getDatabaseURL());
				 query.setUsername("root");
				 query.setPassword("initial1");
				 query.setQuery("select * from testdata");
				query.connectToDatabase();
				data = query.retrieveInstances();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		// setting class attribute
			
			 FPGrowth model = new FPGrowth();
			 model.setDelta(0.01);
		     model.setLowerBoundMinSupport(0.01);
		     model.setMinMetric(0.5);
		     
			 model.setFindAllRulesForSupportLevel(true);
			 model.setNumRulesToFind(1000);
			
			 try {
				model.buildAssociations(data);
				System.out.println(model.getAssociationRules().getNumRules()+"");
			 } catch ( Exception e) {
				 e.printStackTrace();
			 }
			 
			 System.out.println("Start NN Algorithm");
			
			 
		NNAlgorithm nn = new NNAlgorithm(new LikeAssociationJoint(model,dao));

		List<Neighbour> neighbours = nn.computeNeighbours(testuser,	dao.getAllUserswithoutLastfm());
		
		for (int i = 0; i < neighbours.size(); i++) {
			if(neighbours.get(i).getDistance() > 0.1) System.out.println(neighbours.get(i).toString());
		}
		Caller.getInstance().setUserAgent("tst");
		
			Collection<User> users;
			//User u = User.getInfo("viggi",  APIKEY);
			
			//testuser.setSongs(getSongsForUser(testuser, u, dao));
			//testuser.setLastfmid("viggi");
			//dao.refreshUser(testuser);
			users =  User.getNeighbours("bluetiger2k8", APIKEY);
			int i = 0;
			Collection<Track> tracks;
		  
			System.out.println(neighbours.size());
			
			Musicuser muser = null;
			
			//user get tracks
			List<Song> songs;
			
		for (User user : users) {
			System.out.println("Get Users");
			i++;
			muser = neighbours.get(i).getUser();
			songs = getSongsForUser(muser, user, dao);
			if(songs== null) continue;
		  	muser.setSongs(songs);
		  	dao.refreshUser(muser);
		  	
		}
		
		System.out.println(users.size());  
		  //User.getRecentTracks("test", 1, 200,  APIKEY);
	}
	
	public static List<Song> getSongsForUser(Musicuser muser , User user, DatabaseUserDAO dao){
		
		HashMap<String, Track> hmap = new HashMap<String, Track>();
		List<Track> usertracks = new ArrayList<Track>();
		PaginatedResult<Track> resultset = null;
		Collection<Track> intermediate;
		int page = 1;
		
		if (muser.getLastfmid() != null) return null;
		muser.setLastfmid(user.getName());
		usertracks = new ArrayList<Track>();
		System.out.println(user.getId());
		try {
			resultset = User.getRecentTracks(user.getName(), page, 200,  APIKEY);
		} catch(Exception e){
			e.printStackTrace();
		
		}
		intermediate = resultset.getPageResults();
		//if (intermediate.size()== 0)return null;
		for (Track track : intermediate) {
		if( ! hmap.containsKey(track.getUrl())){
			if(track.getUrl()!= null){
				hmap.put(track.getUrl(),track);
				usertracks.add(track);
			}
		}
	}
	


	resultset = User.getLovedTracks(user.getName(), APIKEY);

	intermediate = resultset.getPageResults();
	for (Track track : intermediate) {
		
		if( ! hmap.containsKey(track.getUrl())){
			if(track.getUrl()!= null){
				hmap.put(track.getUrl(),track);
				usertracks.add(track);
			}
		}
	}
	
	//set tracks of last fm
	
	List<Song> songs = new ArrayList<Song>();
 	Song song = null;
 	//Convert Track list to Song list
 	System.out.println("Add:"+usertracks.size());
  	for (Track track : usertracks) {
  		
  		//first check if the song is in the database
  		
  		if(dao.songExists(track.getUrl())) {
  			song = dao.getSong(track.getUrl());
  		} else {
  			song = new Song();
  			
  			if(track.getUrl() == null || track.getUrl().equals("")){
  				continue;
  			}else {
  				song.setId(track.getId());
  			}
  			song.setId(track.getUrl());
  			song.setInterpret(track.getArtist());
  			song.setName(track.getName());
  			song.setGenre("music");
  		}
  		songs.add(song);
  	
  		}
  		return songs;
	}

}
